"""
Case Type   : mot
Case Name   : 关闭enable_mot_server参数，gsql -f导入文件包含mot表、视图等，合理报错
Create At   : 2025/4/8
Owner       : @li-xin12345
Description : (编译带mot，不编译ENABLE_X86_RDTSCP，对应转测包)
    1、设置enable_incremental_checkpoint=off，enable_mot_server=off
    2、准备sql文件
    3、gsql -f sql  导入步骤2中sql文件
    4、清理环境
Expect      :
    1、成功
    2、成功
    3、合理报错
    4、成功
History     :
"""

import os
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class MotTest(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.node_pri = Node('PrimaryDbUser')
        self.param_names = ['enable_incremental_checkpoint',
                            'enable_mot_server']
        self.default_values = [self.common.show_param(i) for i in
                               self.param_names]
        self.tb_name = 't_guc_mot_0032'
        self.view_name = 'v_guc_mot_0032'
        self.index_name = 'i_guc_mot_0032'
        self.file_path = os.path.join(os.path.dirname(macro.DB_ENV_PATH),
                                      f"{self.tb_name}.sql")

    def test_mot(self):
        text = '-----step1:设置enable_incremental_checkpoint=off，' \
               'enable_mot_server=off;expect:成功-----'
        self.log.info(text)
        for i in self.param_names:
            res = self.pri_sh.execute_gsguc(
                'set', self.constant.GSGUC_SUCCESS_MSG, f'{i}=off')
            self.log.info(res)
            self.assertTrue(res, '执行失败：' + text)

        res = self.pri_sh.restart_db_cluster()
        self.log.info(res)
        self.assertTrue(res, '执行失败：' + text)
        status = self.pri_sh.get_db_cluster_status()
        self.assertTrue("Normal" or "Degrade" in status)
        res = [self.common.show_param(i) for i in self.param_names]
        self.log.info(res)
        self.assertEqual(['off', 'off'], res, '执行失败：' + text)

        text = '-----step2:准备sql文件;expect:成功-----'
        self.log.info(text)
        sql = f'''drop foreign table if exists {self.tb_name} cascade;
        create foreign table {self.tb_name} (id int primary key, 
        name varchar(100) not null,age int not null default 0);
        create index {self.index_name} on {self.tb_name} (name);
        insert into {self.tb_name} (id, name, age) values (1, 'alice', 25), 
        (2, 'bob', 30), (3, 'charlie', 35);
        select * from {self.tb_name} where age > 30;
        update {self.tb_name} set age = 26 where id = 1;
        begin;
        insert into {self.tb_name} (id, name, age) values (4, 'david', 40);
        commit;
        create or replace view {self.view_name} as
        select id, name, age from {self.tb_name} where age > 30;
        select * from {self.view_name};
        '''
        cmd = f'''echo "{sql}" > {self.file_path}; cat {self.file_path}'''
        self.log.info(cmd)
        res = self.node_pri.sh(cmd).result()
        self.log.info(res)

        text = '-----step3:gsql -f sql 导入步骤2中sql文件;expect:合理报错-----'
        self.log.info(text)
        cmd = f'''source {macro.DB_ENV_PATH};
        gsql -d {self.node_pri.db_name} -f {self.file_path}
        '''
        self.log.info(cmd)
        res = self.node_pri.sh(cmd).result()
        self.log.info(res)
        self.assertIn('ERROR', res, '执行失败：' + text)
        self.assertIn('MOT engine is not initialized', res, '执行失败：' + text)

    def tearDown(self):
        text = '-----step4:清理环境; expect:成功-----'
        self.log.info(text)
        sql = f'''drop foreign table if exists {self.tb_name} cascade;
        checkpoint;
        '''
        drop_res = self.pri_sh.execut_db_sql(sql)
        self.log.info(drop_res)
        res = [self.common.show_param(i) for i in self.param_names]
        self.log.info(res)
        if res != self.default_values:
            for i, param_name in enumerate(self.param_names):
                res = self.pri_sh.execute_gsguc(
                    'set', self.constant.GSGUC_SUCCESS_MSG,
                    f'{param_name}={self.default_values[i]}')
                self.log.info(res)
            restart_res = self.pri_sh.restart_db_cluster()
            self.log.info(restart_res)
            status = self.pri_sh.get_db_cluster_status()
            self.log.info(status)
            show_param = [self.common.show_param(i) for i in self.param_names]
            self.log.info(show_param)
            self.assertEqual(self.default_values, show_param, '执行失败：' + text)
            self.assertTrue(restart_res, '执行失败：' + text)

        cmd = f'rm -rf {self.file_path};' \
              f'if [ -d {self.file_path} ]; ' \
              f'then echo "exists"; else echo "not exists"; fi'
        rm_res = self.common.get_sh_result(self.node_pri, cmd)
        self.assertIn('not exists', rm_res, '执行失败：' + text)
        self.assertIn(self.constant.DROP_FOREIGN_SUCCESS_MSG, drop_res,
                      '执行失败：' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')